package cn.iocoder.yudao.module.iot.controller.app.room;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import cn.iocoder.yudao.module.iot.controller.app.room.vo.IotAppRoomCreateReqVO;
import cn.iocoder.yudao.module.iot.controller.app.room.vo.IotAppRoomRespVO;
import cn.iocoder.yudao.module.iot.controller.app.room.vo.IotAppRoomUpdateReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.room.vo.IotRoomPageReqVO;
import cn.iocoder.yudao.module.iot.controller.admin.room.vo.IotRoomSaveReqVO;
import cn.iocoder.yudao.module.iot.dal.dataobject.room.IotRoomDO;
import cn.iocoder.yudao.module.iot.service.room.IotRoomService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "用户 APP - IoT 房间管理")
@RestController
@RequestMapping("/iot/room")
@Validated
@Slf4j
//@PreAuthorize("@ss.hasAnyUserType('MEMBER', 'ADMIN')")
public class IotAppRoomController {

    @Resource
    private IotRoomService roomService;

    @GetMapping("/page")
    @Operation(summary = "获得当前用户的房间分页")
    public CommonResult<PageResult<IotAppRoomRespVO>> getRoomPage(@Valid IotRoomPageReqVO pageReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        log.info("[IotAppRoomController] 获取房间分页请求，用户ID: {}, 查询条件: {}", userId, pageReqVO);
        if (userId == null) {
            log.warn("[IotAppRoomController] 用户未登录，返回空分页");
            return success(new PageResult<>());
        }
        pageReqVO.setUserId(userId);
        PageResult<IotRoomDO> pageResult = roomService.getRoomPage(pageReqVO);
        log.info("[IotAppRoomController] 获取房间分页成功，数量: {}", pageResult.getList().size());
        return success(BeanUtils.toBean(pageResult, IotAppRoomRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得当前用户的房间列表")
    public CommonResult<List<IotAppRoomRespVO>> getRoomList() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        log.info("[IotAppRoomController] 获取房间列表请求，用户ID: {}", userId);
        if (userId == null) {
            log.warn("[IotAppRoomController] 用户未登录，返回空列表");
            return success(List.of());
        }
        List<IotRoomDO> list = roomService.getRoomListByUserId(userId);
        log.info("[IotAppRoomController] 获取房间列表成功，数量: {}", list.size());
        return success(BeanUtils.toBean(list, IotAppRoomRespVO.class));
    }

    @GetMapping("/get")
    @Operation(summary = "获得房间详情")
    @Parameter(name = "id", description = "房间编号", required = true, example = "1024")
    public CommonResult<IotAppRoomRespVO> getRoom(@RequestParam("id") Long id) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        log.info("[IotAppRoomController] 获取房间详情请求，房间ID: {}, 用户ID: {}", id, userId);
        if (userId == null) {
            log.warn("[IotAppRoomController] 用户未登录，返回null");
            return success(null);
        }
        IotRoomDO room = roomService.getRoom(id);
        if (room == null || !room.getUserId().equals(userId)) {
            log.warn("[IotAppRoomController] 房间不存在或不属于当前用户，房间ID: {}, 用户ID: {}", id, userId);
            return success(null);
        }
        log.info("[IotAppRoomController] 获取房间详情成功，房间ID: {}", id);
        return success(BeanUtils.toBean(room, IotAppRoomRespVO.class));
    }

    @PostMapping("/create")
    @Operation(summary = "创建房间", description = "创建房间")
    public CommonResult<Long> createRoom(@Valid @RequestBody IotAppRoomCreateReqVO createReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        log.info("[IotAppRoomController] 创建房间请求，用户ID: {}, 房间信息: {}", userId, createReqVO);
        if (userId == null) {
            log.warn("[IotAppRoomController] 用户未登录，创建失败");
            return success(null);
        }
        //查询该房间是否存在
        List<IotRoomDO> roomListByUserId = roomService.getRoomListByUserId(userId);
        for (IotRoomDO room : roomListByUserId) {
            if (room.getName().equals(createReqVO.getName())) {
                log.warn("[IotAppRoomController] 房间已存在，创建失败");
                return success(null);
            }
        }
        IotRoomSaveReqVO saveReqVO = new IotRoomSaveReqVO();
        saveReqVO.setName(createReqVO.getName());
        saveReqVO.setType(createReqVO.getType());
        saveReqVO.setParentId(createReqVO.getParentId());
        saveReqVO.setUserId(userId);
        Long roomId = roomService.createRoom(saveReqVO);
        log.info("[IotAppRoomController] 房间创建成功，房间ID: {}", roomId);
        return success(roomId);
    }

    @PutMapping("/update")
    @Operation(summary = "更新房间", description = "更新房间信息")
    public CommonResult<Boolean> updateRoom(@Valid @RequestBody IotAppRoomUpdateReqVO updateReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        if (userId == null) {
            log.warn("用户未登录，操作失败");
            return CommonResult.error(401, "用户未登录");
        }
        IotRoomDO room = roomService.getRoom(updateReqVO.getId());
        if (room == null || !room.getUserId().equals(userId)) {
            log.warn("[IotAppRoomController] 房间不存在或不属于当前用户，房间ID: {}, 用户ID: {}", updateReqVO.getId(), userId);
            return success(false);
        }
        IotRoomSaveReqVO saveReqVO = new IotRoomSaveReqVO();
        saveReqVO.setId(updateReqVO.getId());
        saveReqVO.setName(updateReqVO.getName());
        saveReqVO.setType(updateReqVO.getType());
        saveReqVO.setParentId(updateReqVO.getParentId());
        saveReqVO.setUserId(userId);
        roomService.updateRoom(saveReqVO);
        log.info("[IotAppRoomController] 房间更新成功，房间ID: {}", updateReqVO.getId());
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除房间", description = "删除房间信息")
    @Parameter(name = "id", description = "房间编号", required = true)
    public CommonResult<Boolean> deleteRoom(@RequestParam("id") Long id) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        if (userId == null) {
            log.warn("用户未登录，操作失败");
            return CommonResult.error(401, "用户未登录");
        }
        IotRoomDO room = roomService.getRoom(id);
        if (room == null || !room.getUserId().equals(userId)) {
            log.warn("[IotAppRoomController] 房间不存在或不属于当前用户，房间ID: {}, 用户ID: {}", id, userId);
            return success(false);
        }
        roomService.deleteRoom(id);
        log.info("[IotAppRoomController] 房间删除成功，房间ID: {}", id);
        return success(true);
    }

    @GetMapping("/list-by-parent")
    @Operation(summary = "获得当前用户的子房间列表")
    @Parameter(name = "parentId", description = "父级房间编号", example = "1024")
    public CommonResult<List<IotAppRoomRespVO>> getRoomListByParentId(
            @RequestParam(value = "parentId", required = false) Long parentId) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        if (userId == null) {
            log.warn("用户未登录，操作失败");
            return CommonResult.error(401, "用户未登录");
        }
        List<IotRoomDO> list = roomService.getRoomListByUserIdAndParentId(userId, parentId);
        log.info("[IotAppRoomController] 获取子房间列表成功，数量: {}", list.size());
        return success(BeanUtils.toBean(list, IotAppRoomRespVO.class));
    }

    @GetMapping("/list-by-user")
    @Operation(summary = "根据用户ID获取房间列表")
    public CommonResult<List<IotAppRoomRespVO>> getRoomListByUser() {
        Long userId = SecurityFrameworkUtils.getLoginUserId();

        if (userId == null) {
            log.warn("用户未登录，操作失败");
            return CommonResult.error(401, "用户未登录");
        }
        List<cn.iocoder.yudao.module.iot.dal.dataobject.room.IotRoomDO> list = roomService.getRoomListByUserId(userId);
        return success(cn.iocoder.yudao.framework.common.util.object.BeanUtils.toBean(list, IotAppRoomRespVO.class));
    }
} 